from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_inner, aq_parent
from Products.LinguaPlone.interfaces import ITranslatable

from time import time
from plone.memoize import ram
import re

from plonetheme.apkntheme import APKNThemeMessageFactory as _
from plonetheme.apkntheme.settings import *
from plonetheme.apkntheme import logger

from zope.component import getMultiAdapter
from plone.app.layout.navigation.interfaces import INavigationQueryBuilder
from plone.app.layout.navigation.interfaces import INavtreeStrategy
from plone.app.layout.navigation.navtree import buildFolderTree

NAV_PORTAL_TYPES = ['ATBooleanCriterion', 'ATCurrentAuthorCriterion', 'ATDateCriteria', 'ATDateRangeCriterion', 'ATListCriterion', 'ATPathCriterion', 'ATPortalTypeCriterion', 'ATReferenceCriterion', 'ATRelativePathCriterion', 'ATSelectionCriterion', 'ATSimpleIntCriterion', 'ATSimpleStringCriterion', 'ATSortCriterion', 'Attribute', 'AttributeCollection', 'AttributeManager', 'Blog Entry', 'BungeniHelpCenterGlossary', 'BungeniHelpCenterReferenceManual', 'BungeniHelpCenterReferenceManualPage', 'BungeniHelpCenterReferenceManualSection', 'BungeniHelpCenterTutorial', 'BungeniHelpCenterTutorialPage', 'Category', 'CategoryManager', 'CompositePage', 'Document', 'Event', 'Favorite', 'FeedfeederFolder', 'FieldsetFolder', 'File', 'Folder', 'FolderishDocument', 'FormBooleanField', 'FormCommaCriterion', 'FormCustomScriptAdapter', 'FormDateField', 'FormFileField', 'FormFixedPointField', 'FormFolder', 'FormIntegerField', 'FormLabelField', 'FormLinesField', 'FormMailerAdapter', 'FormMultiSelectionField', 'FormPasswordField', 'FormRichLabelField', 'FormRichTextField', 'FormSaveDataAdapter', 'FormSelectionField', 'FormStringField', 'FormTextField', 'FormThanksPage', 'HelpCenter', 'HelpCenterDefinition', 'HelpCenterErrorReference', 'HelpCenterErrorReferenceFolder', 'HelpCenterFAQ', 'HelpCenterFAQFolder', 'HelpCenterGlossary', 'HelpCenterHowTo', 'HelpCenterHowToFolder', 'HelpCenterInstructionalVideo', 'HelpCenterInstructionalVideoFolder', 'HelpCenterLink', 'HelpCenterLinkFolder', 'HelpCenterReferenceManual', 'HelpCenterReferenceManualFolder', 'HelpCenterReferenceManualPage', 'HelpCenterReferenceManualSection', 'HelpCenterTutorial', 'HelpCenterTutorialFolder', 'HelpCenterTutorialPage', 'Image', 'Large Plone Folder', 'Link', 'MailmanSubForm', 'News Item', 'ParliamentaryDocument', 'PloneGlossary', 'PloneGlossaryDefinition', 'PoiIssue', 'PoiPscTracker', 'PoiResponse', 'PoiTracker', 'Portlet Page', 'PressClip', 'PressContact', 'PressRelease', 'PressRoom', 'Resource', 'Resource Folder', 'TabbedSubpages', 'TaxonomyType', 'Topic', 'Window', 'WindowZTool', 'mxmContacts', 'mxmContactsGroup', 'mxmContactsOrganization', 'mxmContactsPerson', 'mxmContactsResource', 'rss_feed', 'rss_history', 'rss_instance', 'rss_item', 'rss_manager', 'sdotNewsFolder']

class CustomNavigator(BrowserView):
	
	def filter_app(self, app_id):
		path = aa = self.request.form.get('path')
		application_id = app_id
		regex_application_id = ''
		if path:
			for app_re in APPLICATION_RE:
				if re.match(app_re[1], path):
					regex_application_id = app_re[0]
					break
		if regex_application_id:
			application_id = regex_application_id
		logger.debug("Setting application ID to %s", application_id)
		return application_id
	
	def activeApplication(self):
		aa = self.request.form.get('app_id')
		return aa

	def getSearchControl(self):
		searchControl = None
		active_app = self.activeApplication()
		if SEARCH_CONTROLS.has_key(active_app):
			searchControl = SEARCH_CONTROLS[active_app]
			if (not searchControl.has_key(u'method')):
				searchControl['method'] = u'GET'
		else:
			logger.debug("No search control to show for this request")
		return searchControl

	@ram.cache(lambda *args: time() //  CACHE_SECONDS_FULLDAY)
	def getPublicSpaces(self):
		SPACE_LIST = [{'id':d[0],'text':d[1],'title': d[2], 
		'link': d[3], 'target': d[4]} for d in PUBLIC_SPACES]
		return SPACE_LIST

	def getPrivateWorkspaces(self):
		country_code = u'fpl'
		pm = getToolByName(self.context, 'portal_membership')
		if pm:
			member = pm.getAuthenticatedMember()
			if member:
				user_country_code = member.getProperty('my_country', 
				None)
				if user_country_code:
					country_code = '.'.join((user_country_code, \
					country_code))
		SPACE_LIST = [{ 'id':d[0], 
		'link':d[1].replace('@@COUNTRY_CODE', country_code.lower()), 
		'text':d[2], 
		'title':d[3], 
		'target':d[4], 
		'active': self.isAppActive(d[0]),
		'show': d[5] and self.displayWorkspace(d[0].upper()) }
		for d in PRIVATE_SPACES]
		return SPACE_LIST

	def check_url(self, test_str):
		match = False
		rpath = self.request.form.get('path')
		if test_str in str(rpath):
			match = True
		return match
		
	def isAppActive(self,test_id):
		app_id = self.activeApplication()
		if(test_id == 'apkn'):
			if self.check_url('apex'):
				return ''
			else:
				if app_id == 'apkn':
					return CURRECT_ACTIVE_APP
				else:
					return ''
				return CURRECT_ACTIVE_APP
		elif (test_id == 'apex'):
			if self.check_url('/apex/'):
				return CURRECT_ACTIVE_APP
			else:
				return ''
		else:
			if test_id == app_id:
				return CURRECT_ACTIVE_APP
			else:
				return ''
	
	def displayWorkspace(self, workspaceName):
		show = True
		
		if WORKSPACE_MAPPINGS.has_key(workspaceName):
			groupName = WORKSPACE_MAPPINGS[workspaceName]
			pm = getToolByName(self.context, u'portal_membership')
			member = pm.getAuthenticatedMember() 
			if (pm and member):
				member_id = member.getId()
				group_memberships = member.getGroups()
				if group_memberships:
					if groupName in group_memberships:
						show = True
					else:
						show = False
		return show
	
	def isUserAnonymous(self):
		pm = getToolByName(self.context, 'portal_membership')
		anon = pm.isAnonymousUser()
		return anon

	def getNavigationLogoPath(self):
		nav_logo_path = "/++resource++media-logos/ybrand/p/n/apkn-portal.png"
		base_path = "/++resource++media-logos/ybrand/p/n/"
		app_id = self.activeApplication()
		active_app = self.filter_app(app_id)
		if active_app is not None:
			nav_logo_path = "%s%s.png" %(base_path, active_app)
		return nav_logo_path
		
	def getNavStyle(self):
		logo_path = ""
		if self.isUserAnonymous():
			logo_path = self.getAnonLogo()
		else:
			logo_path = self.getNavigationLogoPath()
		st = "background:url('%s') no-repeat left center;"\
		 %(logo_path)
		return st

	def getAnonLogo(self):
		nav_logo_path = "/++resource++media-logos/ybrand/a/n/apkn-portal.png"
		base_path = "/++resource++media-logos/ybrand/a/n/"
		app_id = self.activeApplication()
		active_app = self.filter_app(app_id)
		if active_app:
			nav_logo_path = "%s%s.png" %(base_path, active_app)
		return nav_logo_path

	def get_languages(self):
		if self.activeApplication() is not None:
			lang_tool = getToolByName(self, 'portal_languages', None)
			if lang_tool is not None:
				return lang_tool.getSupportedLanguages()
		else:
			return None

class renderErrorPage(BrowserView):
		def getErrorCode(self):
			code = self.request.form.get("error")
			return str(code)
		def isPageError(self):
			status = self.getErrorCode() in PAGE_ERRORS
			return status
		def isError404(self):
			status = self.getErrorCode() in NOT_FOUND_ERRORS
			return status

class CommonFooter(BrowserView):
	def getTime(self):
		from time import localtime
		return localtime().tm_year


class ConferenceHeader(BrowserView):
	'''
	Render conference header
	'''
	def getContextLanguage(self):
		language_tool = getToolByName(self.context, 'portal_languages')
		if language_tool:
			return language_tool.getLanguageBindings()[0]
		else:
			return u'en'

	def getContextObject(self):
		path = self.request.form.get('path')
		path = '/Plone' + path
		current_object = None
		ob_meta = None
		try:
			current_object = self.context.restrictedTraverse(path)
			ob_meta = current_object.meta_type
			while (ob_meta not in ['HelpCenterReferenceManual', 'ATFolder']):
				current_object = aq_parent(current_object)
				ob_meta = current_object.meta_type
		except:
			logger.error("Could not traverse to @@ %s", path)
		return current_object

	def getContextNavTree(self):
		the_context = self.getContextObject()
		if the_context:
			qpath = '/'.join(the_context.getPhysicalPath())
			query = {'path': qpath, 'portal_types': NAV_PORTAL_TYPES, 
			'review_state':'published'}
			nav_tree = buildFolderTree(the_context, obj=the_context, 
			query=query)
			q_path = self.request.form.get('path','$$$$$$$')
			nav_tree_children = nav_tree['children']
			with_selected_marked = []
			for child in nav_tree_children:
				if child['item'].getURL().endswith(q_path):
					child['currentItem'] = True
				with_selected_marked.append(child)
			nav_tree['children'] = with_selected_marked
			return nav_tree
		else:
			return {'children':[]}

	def getConferenceUIMeta(self):
		conf_id = self.getConferenceDocumentId(default_language = True)
		conf_meta = ('red','bgCfred',)
		if conf_id:
			conf_meta = CONFERENCE_UI_SETTINGS[conf_id]
		return conf_meta

	def getSponsors(self):
		#id, title
		conf_id = self.getConferenceDocumentId(default_language = True)
		sponsors = []
		if conf_id:
			sponsors = [ALL_SPONSORS[s_id] 
			for s_id in CONFERENCE_SPONSORS[conf_id]]
		return [{'id': s[0],'title': s[1], 'link': s[2]} 
		for s in sponsors]

	def getConferenceDocumentId(self, default_language = False):
		conf_id = None
		try:
			if default_language:
				conf_document = self.getConferenceDocument()
				if ITranslatable.providedBy(conf_document):
					original_trans = conf_document.getTranslation('en')
					if original_trans:
						conf_id = original_trans.getId()
			else:
				conf_id = self.getConferenceDocument().getId()
		except:
			pass
		return conf_id

	def getConferenceDocument(self):
		path = self.request.form.get('path')
		path = '/Plone' + path
		current_object = self.context.restrictedTraverse(path)
		ob_meta = current_object.meta_type
		while (ob_meta not in ['HelpCenterReferenceManual', 'ATFolder']):
			current_object = aq_parent(current_object)
			ob_meta = current_object.meta_type
		return current_object
	
	def getConferenceTitle(self):
		conf_title = _("This document has no heading")
		try:
			conf_title = self.getConferenceDocument().title
		except:
			pass
		return conf_title



class DspacePortlet(BrowserView):
	'''
	Render DSPace content navigation Portlet
	'''
